import React, { JSX } from 'react';
import { NulCommonOperations, NulDialog } from '../../components/NulDialog';
import { InventoryEntry, TransferInventory, Warehouse, transferInventory } from '../../actions/InventoryManagement';
import { TableContainer, Table, TableHead, TableRow, Box, TableBody, TableFooter, FormControl, Autocomplete, TextField, InputBase } from '@mui/material';
import { NulHeaderTableCell, NulTableCell } from '../../components/NulHeaderTable';
import { WarehouseEntry } from '../../actions/WarehouseManagement';
import { replaceElementFromArray } from '../../util/Arrays';
import { useAppDispatch } from '../../actions/hook';

interface TransferInventoryDialogProps {
  open: boolean;
  onClose: () => void;
  warehouseId: number
  selectedInventories: InventoryEntry[];
  warehouseEntries: WarehouseEntry[];
}

interface WarehouseOption {
  label: string;
  id: number;
}

interface Inventory {
  row: number;
  id: number;
  name: string;
}

function buildOptions(warehouseEntries: Warehouse[]): WarehouseOption[] {
  const result: WarehouseOption[] = [];
  for (let i = 0; i < warehouseEntries.length; ++i) {
    result.push({ label: warehouseEntries[i].name, id: warehouseEntries[i].id });
  }
  return result;
}

function TransferInventoryDialog(props: TransferInventoryDialogProps): JSX.Element {
  const { open, onClose, warehouseId, selectedInventories, warehouseEntries } = props;

  const dispatch = useAppDispatch();

  const options = buildOptions(warehouseEntries);

  const [value, setValue] = React.useState<WarehouseOption | null>(null);

  const [inventoryList, setInventoryList] = React.useState<Inventory[]>([]);
  const [quantityList, setQuantityList] = React.useState<string[]>([]);

  const handlePositiveClicked = () => {
    if (value !== null) {
      const transferList: TransferInventory[] = [];
      for (let i = 0; i < inventoryList.length; ++i) {
        transferList.push({
          id: inventoryList[i].id,
          quantity: parseInt(quantityList[i]),
          warehouseId
        });
      }
      dispatch(transferInventory({ transferRequests: transferList, targetId: value.id }));
    }
    onClose();
  };

  React.useEffect(() => {
    const inventories: Inventory[] = [];
    const quantities: string[] = [];
    for (let i = 0; i < selectedInventories.length; ++i) {
      inventories.push({ row: i, id: selectedInventories[i].id, name: selectedInventories[i].name });
      quantities.push(selectedInventories[i].quantity.toString());
    }
    setInventoryList(inventories);
    setQuantityList(quantities);
  }, [selectedInventories]);

  return (
    <NulDialog
      title='Transfer Inventory'
      open={open}
      onClose={onClose}
      operations={
        <NulCommonOperations
          onPositiveClicked={handlePositiveClicked}
          onNegativeClicked={onClose}
          positiveText='Transfer'
        />
      }
    >
      <Box sx={{
        paddingTop: '5px', paddingBottom: '15px', display: 'flex', flexDirection: 'row', height: '40px',
        alignItems: 'center'
      }}>
        <Box sx={{ flexGrow: 0, paddingRight: '15px' }}>
          Transfer products to
        </Box>
        <Box sx={{ flexGrow: 1 }}>
          <FormControl fullWidth size='small'>
            <Autocomplete
              options={options}
              getOptionLabel={option => option.label}
              renderInput={(param) => <TextField {...param} />}
              value={value}
              onChange={(event, value) => { setValue(value); }}
              fullWidth={true}
              size='small'
            />
          </FormControl>
        </Box>
      </Box>
      <TableContainer
        sx={{
          width: '100%'
        }}
      >
        <Table
          stickyHeader
          sx={{
            border: '1px solid #DFE4E8',
            borderRadius: '8px',
            fontFamily: 'Open Sans',
            fontStyle: 'normal',
          }}
        >
          <TableHead sx={{ border: '8px 8px 0px 0px' }}>
            <TableRow sx={{
              height: '42px',
              padding: 0,
              width: '100%',
              display: 'flex',
              alignItems: 'center',
            }}>
              <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                <NulHeaderTableCell sx={{ paddingLeft: '30px', width: '20%' }}>
                  ID
                </NulHeaderTableCell>
                <NulHeaderTableCell sx={{ width: '50%' }}>
                  Name
                </NulHeaderTableCell>
                <NulHeaderTableCell sx={{ width: '30%' }}>
                  Quantity
                </NulHeaderTableCell>
              </Box>
            </TableRow>
          </TableHead>
          <TableBody
            sx={{
              minHeight: '320px', maxHeight: '320px', display: 'block', overflowY: 'auto'
            }}
          >
            {inventoryList.map(row => {
              return (
                <TableRow
                  key={row.id}
                  sx={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    height: '42px'
                  }}
                >
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                    <NulTableCell sx={{ paddingLeft: '30px', width: '20%' }}>
                      {row.id}
                    </NulTableCell>
                    <NulTableCell sx={{ width: '50%' }}>
                      {row.name}
                    </NulTableCell>
                    <NulTableCell sx={{ width: '30%' }}>
                      <InputBase placeholder='Quantity' size='small' fullWidth={true}
                        value={quantityList[row.row]}
                        onChange={(action) => { 
                          const value: string = action.target.value;
                          setQuantityList(replaceElementFromArray(quantityList, row.row, value));
                        }}
                        sx={{
                          '& .MuiInputBase-input': {
                            'padding': 0
                          }
                        }}
                        inputProps={{
                          inputRoot: {
                            border: 'none',
                            boxShadow: 'none'
                          }
                        }} />
                    </NulTableCell>
                  </Box>
                </TableRow>
              );
            })}
          </TableBody>
          <TableFooter
            sx={{
              minHeight: '34px',
              maxHeight: '44px',
              display: 'block',
              backgroundColor: '#F1F3F5',
              borderRadius: '0px 0px 8px 8px',
            }}
          ></TableFooter>
        </Table>
      </TableContainer>
    </NulDialog>
  );
}

export default TransferInventoryDialog;